package org.example.webaiproject05.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.webaiproject05.pojo.Dept;
import org.example.webaiproject05.pojo.Result;
import org.example.webaiproject05.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {
//    private static final Logger log = LoggerFactory.getLogger(DeptController.class);//代码是固定的唯一变动的是字节码
    @Autowired
   private DeptService deptService;
    @RequestMapping
    public Result list() {
//        System.out.println("查询所有的部门数据");
        log.info("查询所有的部门数据");
        List<Dept>deptList =deptService.findAll();
        return Result.success(deptList);
    }
    //删除部门
    //方式一HttpServletRequest
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request) {
//        String idStr = request.getParameter("id");
//
//        // 判断参数是否为空
//        if (idStr == null || idStr.trim().isEmpty()) {
//            return Result.error("部门ID不能为空");
//        }
//
//        try {
//            int id = Integer.parseInt(idStr);
//            System.out.println("删除部门" + id);
//            return Result.success();
//        } catch (NumberFormatException e) {
//            return Result.error("无效的部门ID");
//        }
//    }
    //删除部门
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request){
//        request.getParameter("id");
//        int id = Integer.parseInt(request.getParameter("id"));
//        System.out.println(" 删除的部门"+id);
//        return Result.success();
//    }

    @DeleteMapping
    public Result delete(Integer id) {
//        System.out.println("删除的部门" + id);
        log.info("删除的部门：{}", id);
        deptService.deleteById(id);
        return Result.success();
    }
    //新增部门
    @PostMapping
    public Result add(@RequestBody Dept dept){
//        System.out.println("新增的部门"+dept);
        log.info("新增的部门:{}", dept);
        deptService.add(dept);
        return Result.success();
//修改部门


    }
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id){
//        System.out.println("根据ID查询部门"+id);
        log.info("根据ID查询部门:{}", id);
         Dept dept =deptService.getById(id);
        return  Result.success(dept);
    }

//修改部门数据
    @PutMapping
    public Result update(@RequestBody Dept dept){
//        System.out.println("修改的部门"+dept);
        log.info("修改的部门：{}", dept);
        deptService.update(dept);
        return Result.success();



                            
    }

}
